<template>
  <el-dialog
    :title="dialogTitle"  
    :visible.sync="dialogVisible"
  >
    <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
      <el-form-item label="小区管理员" prop="admin">
        <el-input v-model="form.admin" placeholder="请输入小区管理员"></el-input>
      </el-form-item>
      <el-form-item label="小区名称" prop="districtName">
        <el-input v-model="form.districtName" placeholder="请输入小区名称"></el-input>
      </el-form-item>
      <el-form-item label="坐落地址" prop="address">
        <el-input v-model="form.address" placeholder="请输入坐落地址"></el-input>
      </el-form-item>
      <el-form-item label="占地面积 (m²)" prop="area">
        <el-input v-model.number="form.area" type="number" placeholder="请输入占地面积"></el-input>
      </el-form-item>
      <el-form-item label="开发商名称" prop="developerName">
        <el-input v-model="form.developerName" placeholder="请输入开发商名称"></el-input>
      </el-form-item>
      <el-form-item label="物业公司名称" prop="propertyCompany">
        <el-input v-model="form.propertyCompany" placeholder="请输入物业公司名称"></el-input>
      </el-form-item>
      <el-form-item label="绿化率 (%)" prop="greeningRate">
        <el-input v-model.number="form.greeningRate" type="number" placeholder="请输入绿化率"></el-input>
      </el-form-item>
      <el-form-item label="总栋数" prop="totalBuildings">
        <el-input v-model.number="form.totalBuildings" type="number" placeholder="请输入总栋数"></el-input>
      </el-form-item>
      <el-form-item label="总户数" prop="totalHouseholds">
        <el-input v-model.number="form.totalHouseholds" type="number" placeholder="请输入总户数"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="小区缩略图" prop="image">
        <el-upload
          class="avatar-uploader"
          action=""
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl" :src="imageUrl" class="avatar" alt="小区缩略图">
          <i v-else class="el-icon-upload avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="小区简介" prop="description">
        <el-input type="textarea" v-model="form.description" :rows="4" placeholder="请输入小区简介"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    editData: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      dialogVisible: this.visible,
      form: {
        admin: '',
        districtName: '',
        address: '',
        area: null,
        developerName: '',
        propertyCompany: '',
        greeningRate: null,
        totalBuildings: null,
        totalHouseholds: null,
        status: 1,
        image: '',
        description: ''
      },
      imageUrl: '',
      rules: {
        admin: [
          { required: true, message: '请输入小区管理员', trigger: 'blur' }
        ],
        districtName: [
          { required: true, message: '请输入小区名称', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入坐落地址', trigger: 'blur' }
        ],
        area: [
          { required: true, message: '请输入占地面积', trigger: 'blur' },
          { type: 'number', message: '占地面积必须为数字值', trigger: 'blur' }
        ],
        developerName: [
          { required: true, message: '请输入开发商名称', trigger: 'blur' }
        ],
        greeningRate: [
          { required: true, message: '请输入绿化率', trigger: 'blur' },
          { type: 'number', message: '绿化率必须为数字值', trigger: 'blur' },
          { validator: (rule, value, callback) => {
              if (value === null || value === undefined || value === '') {
                callback(new Error('请输入绿化率'));
              } else if (value < 0 || value > 100) {
                callback(new Error('绿化率必须在0-100之间'));
              } else {
                callback();
              }
            }, trigger: 'blur' }
        ],
        totalBuildings: [
          { required: true, message: '请输入总栋数', trigger: 'blur' },
          { type: 'number', message: '总栋数必须为数字值', trigger: 'blur' }
        ],
        totalHouseholds: [
          { required: true, message: '请输入总户数', trigger: 'blur' },
          { type: 'number', message: '总户数必须为数字值', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
        // image: [
        //   { required: true, message: '请上传小区缩略图', trigger: 'change' }
        // ]
      }
    };
  },
  computed: {
    dialogTitle() {
      return this.editData ? '编辑' : '添加';
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val;
      if (!val) {
        this.resetForm();
      }
    },
    editData: {
      immediate: true,
      handler(newVal) {
        if (newVal) {
          this.form = { ...newVal };
          this.imageUrl = newVal.image;
        } else {
          this.resetForm();
        }
      }
    }
  },
  methods: {
    openDialog() {
      this.dialogVisible = true;
    },
    handleCloseDialog() {
      this.dialogVisible = false;
      // Reset form values when dialog is closed
      this.$nextTick(() => {
        this.form = { admin: '', districtName: '' };
      });
    },
    resetForm() {
      this.form = {
        admin: '',
        districtName: '',
        address: '',
        area: null,
        developerName: '',
        propertyCompany: '',
        greeningRate: null,
        totalBuildings: null,
        totalHouseholds: null,
        status: 1,
        image: '',
        description: ''
      };
      this.imageUrl = '';
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields();
      }
    },
    handleAvatarSuccess(response, file) {
      // 这里应该处理上传成功后的响应
      // 示例中使用文件的临时URL作为预览
      this.imageUrl = URL.createObjectURL(file.raw);
      this.form.image = this.imageUrl; // 实际项目中应该存储上传后的URL
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    generateShortId() {
      const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
      let result = '';
      for (let i = 0; i < 6; i++) {
        const randomIndex = Math.floor(Math.random() * characters.length);
        result += characters[randomIndex];
      }
      return result;
    },
    handleSubmit() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          // 模拟表单提交
          this.$message({
            type: 'success',
            message: '小区信息添加成功!'
          });
          // 将表单数据发送给父组件
          if (this.editData) {
            // 编辑操作时保持原有的 id 和 districtCode
            this.$emit('submit', {
              ...this.form,
              id: this.editData.id,
              districtCode: this.editData.districtCode,
              creationTime: this.editData.creationTime
            });
          } else {
            // 添加操作
            this.$emit('submit', {
              ...this.form,
              // 生成一个唯一ID
              id: this.generateShortId(),
              // 生成小区编号
              districtCode: `XY${new Date().getFullYear()}${String(new Date().getMonth() + 1).padStart(2, '0')}${String(new Date().getDate()).padStart(2, '0')}${Math.floor(Math.random() * 1000).toString().padStart(3, '0')}`,
              // 添加创建时间
              creationTime: new Date().toISOString().slice(0, 19).replace('T', ' ')
            });
          }
          this.dialogVisible = false;
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }
  }
};
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: #d9d9d9 1px dashed;

}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>